# -*- coding: utf-8 -*-

from flask import render_template, request, session, url_for, redirect, Blueprint

from app import db
from .forms import SigninForm, SignupForm
from .models import Person


mod = Blueprint('person', __name__, url_prefix='/person')

@mod.route('/signup/', methods=['GET', 'POST'])
def signup():
    form = SignupForm()
    if request.method == 'POST':
        if not form.validate():
            return render_template('person/signup.html', form=form)
        else:
            newperson = Person(form.firstname.data, form.lastname.data, form.email.data, form.password.data)
            db.session.add(newperson)
            db.session.commit()
            session['email'] = newperson.email
            return redirect(url_for('article.profile'))

    elif request.method == 'GET':
        return render_template('person/signup.html', form=form)

@mod.route('/signin/', methods=['GET', 'POST'])
def signin():
  form = SigninForm()

  if request.method == 'POST':
    if form.validate() == False:
      return render_template('person/signin.html', form=form)
    else:
      session['email'] = form.email.data
      return redirect(url_for('article.profile'))

  elif request.method == 'GET':
    return render_template('person/signin.html', form=form)

@mod.route('/signout/')
def signout():
    if 'email' not in session:
        return redirect(url_for('person.signin'))
    session.pop('email', None)
    return redirect(url_for('article.index'))
